import { ref, reactive } from 'vue';
export default function() {
	const uniIdCo = uniCloud.importObject("uni-id-co", {
		customUI: true
	})
	let accountLoginForm = null;
	const seconds = 60;
	const mobileBtnLoading = ref(false);
	const showCodeInput = ref(false);
	const codeBtnText = ref('获取验证码');
	const formData = reactive({
		mobile: '',
		code: '',
		captcha: ''
	})
	const rules = {
		mobile: [{
			type: 'string',
			required: true,
			message: '请输入正确的手机号',
			trigger: ['blur', 'change']
		}, {
			validator: (rule, value, callback) => {
				return uni.$uv.test.mobile(value);
			},
			message: '手机号格式错误',
			trigger: ['blur']
		}],
		code: [{
			type: 'string',
			required: true,
			message: '请填写验证码',
			trigger: ['blur', 'change']
		}]
	}
	// 提交登录
	function submit(form, mobileCode, redirectTo) {
		accountLoginForm = form;
		accountLoginForm.validate().then(res => {
			if (!showCodeInput.value) {
				getCode(mobileCode);
				showCodeInput.value = true;
			} else {
				submitLogin(res, redirectTo);
			}
		}).catch(errors => {
			uni.showToast({
				icon: 'error',
				title: '校验失败'
			})
		})
	}
	// 提交登录
	function submitLogin(res, redirectTo) {
		mobileBtnLoading.value = true;
		uniIdCo.loginBySms({
			mobile: formData.mobile,
			code: formData.code,
			captcha: formData.captcha
		}).then(e => {
			getApp().loginSuccess({
				...e,
				showToast: false
			});
			setTimeout(() => {
				redirectTo(true);
			}, 200)
		}).catch(e => {
			uni.$uv.toast(e.message);
			console.log('登录失败：', e.message);
		}).finally(() => {
			mobileBtnLoading.value = false;
		})
	}
	// 检测某字段
	function checkField(name) {
		return new Promise((resolve, reject) => {
			accountLoginForm.validateField('mobile', err => {
				if (err[0]?.message) {
					uni.$uv.toast(err[0]?.message);
					reject('err[0]?.message');
				} else {
					resolve(true);
				}
			})
		})
	}
	// 获取短信验证码
	async function getCode(mobileCode) {
		try {
			if (codeBtnText.value != '获取验证码') return;
			await checkField('mobile');
			sending();
			// 为了更好的体验，直接模拟发送成功
			setTimeout(() => {
				mobileCode.start();
			}, 100)
			uniIdCo.sendSmsCode({
				"mobile": formData.mobile,
				"scene": 'login-by-sms',
				"captcha": formData.captcha
			}).then(result => {
				uni.$uv.toast('短信验证码发送成功');
			}).catch(e => {
				end();
				if (e.code == "uni-id-invalid-sms-template-id") {
					formData.code = "123456"
					uni.$uv.toast('已启动测试模式,详情【控制台信息】');
					console.warn(e.message);
				} else {
					end();
					uni.$uv.toast(e.message);
				}
			})
		} catch (e) {
			console.log(e)
		}
	}
	// 发送中
	function sending() {
		codeBtnText.value = '发送中...';
	}
	// 发送验证码后倒计时开始
	function start() {
		codeBtnText.value = `${seconds}秒重新获取`;
	}
	// 发送验证码后倒计时结束
	function end() {
		codeBtnText.value = '获取验证码';
	}
	// 倒计时
	function codeChange(text) {
		codeBtnText.value = text;
	}
	return {
		showCodeInput,
		mobileLoginFormData: formData,
		mobileLoginRules: rules,
		mobileLoginSubmit: submit,
		codeBtnText,
		getCode,
		seconds,
		start,
		end,
		codeChange,
		mobileBtnLoading
	}
}